<template>
  <div>
    <el-dialog title="供应商选择"
      v-if="showFlag"
      :visible.sync="showFlag"
      :modal= false
      width="80%"
      center
     append-to-body
      >
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商编码" prop="vendorCode">
              <el-input
                v-model="queryParams.vendorCode"
                placeholder="请输入供应商编码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input
                v-model="queryParams.vendorName"
                placeholder="请输入供应商名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商简称" prop="vendorNick">
              <el-input
                v-model="queryParams.vendorNick"
                placeholder="请输入供应商简称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="英文名称" prop="vendorEn">
              <el-input
                v-model="queryParams.vendorEn"
                placeholder="请输入供应商英文名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-select
                v-model="queryParams.enableFlag"
                placeholder="是否启用"
                clearable
                style="width: 215px"
              >
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAddVendor">添加供应商</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table 
        v-loading="loading" 
        :data="vendorList" 
        @current-change="handleCurrent" 
        @row-dblclick="handleRowDbClick"
        @row-click="handleRowClick"
        :row-class-name="tableRowClassName"
        highlight-current-row
      >
        <el-table-column label="供应商编码" align="center" prop="vendorCode" >
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="vendorName" width="150px" :show-overflow-tooltip="true"/>
        <el-table-column label="供应商简称" align="center" prop="vendorNick" />
        <el-table-column label="供应商等级" align="center" prop="vendorLevel" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_vendor_level" :value="scope.row.vendorLevel"/>
          </template>
        </el-table-column>
        <el-table-column label="供应商评分" align="center" prop="vendorScore" />
        <el-table-column label="供应商电话" align="center" prop="tel" />
        <el-table-column label="是否启用" align="center" prop="enableFlag" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.enableFlag"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelect">确 定</el-button>
        <el-button @click="showFlag=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加供应商弹窗 -->
    <el-dialog
      title="添加供应商"
      :visible.sync="addVendorDialogVisible"
      width="60%"
      append-to-body
      @close="cancelAddVendor"
    >
      <el-form ref="addVendorForm" :model="addVendorForm" :rules="addVendorRules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商编码" prop="vendorCode">
              <el-input v-model="addVendorForm.vendorCode" placeholder="请输入供应商编码" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                  active-color="#13ce66"
                  active-text="自动生成"
                  @change="handleAutoGenChange(autoGenFlag)">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="vendorName">
              <el-input v-model="addVendorForm.vendorName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商简称" prop="vendorNick">
              <el-input v-model="addVendorForm.vendorNick" placeholder="请输入供应商简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="vendorEn">
              <el-input v-model="addVendorForm.vendorEn" placeholder="请输入英文名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商等级" prop="vendorLevel">
              <el-select v-model="addVendorForm.vendorLevel" placeholder="请选择供应商等级" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.mes_vendor_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商评分" prop="vendorScore">
              <el-input-number v-model="addVendorForm.vendorScore" :min="0" :max="100" :precision="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="addVendorForm.tel" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addVendorForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="addVendorForm.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网站" prop="website">
              <el-input v-model="addVendorForm.website" placeholder="请输入网站" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人1" prop="contact1">
              <el-input v-model="addVendorForm.contact1" placeholder="请输入联系人1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人1电话" prop="contact1Tel">
              <el-input v-model="addVendorForm.contact1Tel" placeholder="请输入联系人1电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人1邮箱" prop="contact1Email">
              <el-input v-model="addVendorForm.contact1Email" placeholder="请输入联系人1邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="addVendorForm.creditCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-select v-model="addVendorForm.enableFlag" placeholder="请选择是否启用" style="width: 100%">
                <el-option
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="addVendorForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddVendor">确 定</el-button>
        <el-button @click="cancelAddVendor">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVendor, getVendor, delVendor, addVendor, updateVendor } from "@/api/mes/md/vendor";
import { genCode } from "@/api/system/autocode/rule";
export default {
  name: "VendorSelect",
  dicts: ['sys_yes_no','mes_vendor_level'],
  props: {
    itemId: [String, Number]
  },
  data() {
    return {
      showFlag:false,
      selectedVendorId: undefined,
      selectedRow: undefined,
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商表格数据
      vendorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        vendorEn: null,
        vendorDes: null,
        vendorLogo: null,
        vendorLevel: null,
        vendorScore: null,
        address: null,
        website: null,
        email: null,
        tel: null,
        contact1: null,
        contact1Tel: null,
        contact1Email: null,
        contact2: null,
        contact2Tel: null,
        contact2Email: null,
        creditCode: null,
        enableFlag: null,
        mdItemId:null
      },
      // 表单参数
      form: {},
      // 添加供应商弹窗
      addVendorDialogVisible: false,
      // 自动生成编码标志
      autoGenFlag: false,
      // 添加供应商表单
      addVendorForm: {
        vendorCode: '',
        vendorName: '',
        vendorNick: '',
        vendorEn: '',
        vendorLevel: null,
        vendorScore: 0,
        address: '',
        website: '',
        email: '',
        tel: '',
        contact1: '',
        contact1Tel: '',
        contact1Email: '',
        contact2: '',
        contact2Tel: '',
        contact2Email: '',
        creditCode: '',
        enableFlag: 'Y',
        remark: ''
      },
      // 添加供应商表单验证规则
      addVendorRules: {
        vendorCode: [
          { required: true, message: '请输入供应商编码', trigger: 'blur' }
        ],
        vendorName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        vendorLevel: [
          { required: true, message: '请选择供应商等级', trigger: 'change' }
        ],
        enableFlag: [
          { required: true, message: '请选择是否启用', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    console.log('this.itemId--',this.itemId);
    // 使用计算属性或直接使用 prop 值，避免修改
    if (this.itemId) {
      this.queryParams.mdItemId = this.itemId;
      this.getList();
    }
  },
  watch: {
    itemId: {
      handler(newVal) {
        // 避免直接修改 prop，使用新的查询参数对象
        if (newVal) {
          this.queryParams.mdItemId = newVal;
          this.getList();
        }
      },
      immediate: false
    }
  },
  methods: {
    /** 查询供应商列表 */
    getList() {
      this.loading = true;
      return listVendor(this.queryParams).then(response => {
        this.vendorList = response.rows;
        this.total = response.total;
        this.loading = false;
        return response;
      });
    },
    getList1(mdItemId) {
      this.loading = true;
      // 创建新的查询参数对象，避免直接修改
      const queryParams = { ...this.queryParams, mdItemId: mdItemId };
      this.resetForm("queryForm");
      return listVendor(queryParams).then(response => {
        this.vendorList = response.rows;
        this.total = response.total;
        this.loading = false;
        return response;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
        /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCurrent(row){
        if(row){
            this.selectedRow = row;
        }
    },
    //行双击选中
    handleRowDbClick(row){
      if(row){
        this.selectedRow = row;
        console.log('VendorSelect - 双击选择 - selectedRow:', this.selectedRow);
        this.$emit('onSelected',this.selectedRow);
        this.showFlag = false;
      }
    },
    // 单选选中数据
    handleRowChange(row) {
      if(row){
        this.selectedRow = row;
      }
    },
    //确定选中
    confirmSelect(){
        if(this.selectedVendorId ==null || this.selectedVendorId==0){
            this.$notify({
                title:'提示',
                type:'warning',
                message: '请至少选择一条数据!'
            });
            return;
        }
        console.log('VendorSelect - 确认选择 - selectedRow:', this.selectedRow);
        this.$emit('onSelected',this.selectedRow);
        this.showFlag = false;
    },
    // 添加供应商按钮点击
    handleAddVendor() {
      this.addVendorDialogVisible = true;
      this.resetAddVendorForm();
    },
    // 重置添加供应商表单
    resetAddVendorForm() {
      this.addVendorForm = {
        vendorCode: '',
        vendorName: '',
        vendorNick: '',
        vendorEn: '',
        vendorLevel: null,
        vendorScore: 0,
        address: '',
        website: '',
        email: '',
        tel: '',
        contact1: '',
        contact1Tel: '',
        contact1Email: '',
        contact2: '',
        contact2Tel: '',
        contact2Email: '',
        creditCode: '',
        enableFlag: 'Y',
        remark: ''
      };
      // 重置自动生成标志
      this.autoGenFlag = false;
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.addVendorForm) {
          this.$refs.addVendorForm.clearValidate();
        }
      });
    },
    // 提交添加供应商
    submitAddVendor() {
      this.$refs.addVendorForm.validate((valid) => {
        if (valid) {
          addVendor(this.addVendorForm).then(response => {
            // this.$modal.msgSuccess("添加供应商成功");
            // 关闭新增供应商弹窗
            this.addVendorDialogVisible = false;
            
            // 刷新供应商列表
            this.getList().then(() => {
              // 等待列表刷新完成后，自动选中新添加的供应商
              this.$nextTick(() => {
                this.selectedVendorId = response.data.vendorId;
                this.selectedRow = response.data;
                
                // 高亮显示新添加的供应商行
                this.$nextTick(() => {
                  this.highlightNewVendor(response.data.vendorId);
                });
                
                // // 显示提示信息
                // this.$notify({
                //   title: '供应商已添加',
                //   message: `供应商"${response.data.vendorName}"已成功添加并自动选中，您可以点击"确定"按钮确认选择。`,
                //   type: 'success',
                //   duration: 4000,
                //   showClose: true
                // });
              });
            });
            
            // 保持主选择弹窗打开，让用户可以选择新添加的供应商
            // this.showFlag = false; // 注释掉，保持弹窗打开
          }).catch(error => {
            this.$modal.msgError("添加供应商失败：" + (error.message || "请求异常"));
          });
        }
      });
    },
    // 取消添加供应商
    cancelAddVendor() {
      this.addVendorDialogVisible = false;
      this.resetAddVendorForm();
    },
    // 自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('VENDOR_CODE').then(response => {
          this.addVendorForm.vendorCode = response;
        });
      } else {
        this.addVendorForm.vendorCode = '';
      }
    },
    
    // 行点击事件
    handleRowClick(row, column, event) {
      if (row) {
        this.selectedVendorId = row.vendorId;
        this.selectedRow = row;
      }
    },
    // 表格行类名
    tableRowClassName({ row, rowIndex }) {
      if (this.selectedVendorId && row.vendorId === this.selectedVendorId) {
        return 'selected-row';
      }
      return '';
    },
    // 高亮显示新添加的供应商
    highlightNewVendor(vendorId) {
      this.$nextTick(() => {
        const table = this.$el.querySelector('.el-table');
        if (table) {
          const rows = table.querySelectorAll('.el-table__row');
          rows.forEach((row, index) => {
            if (this.vendorList[index] && this.vendorList[index].vendorId === vendorId) {
              // 移除之前的高亮
              row.classList.remove('highlight-new-vendor');
              // 添加新的高亮
              row.classList.add('highlight-new-vendor');
              // 滚动到新添加的供应商行
              row.scrollIntoView({ behavior: 'smooth', block: 'center' });
              
              // 3秒后移除高亮效果
              setTimeout(() => {
                row.classList.remove('highlight-new-vendor');
              }, 6000);
            }
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

/* 高亮显示新添加的供应商 */
::v-deep .highlight-new-vendor {
  background-color: #f0f9ff !important;
  border-left: 3px solid #409eff !important;
}

::v-deep .highlight-new-vendor:hover {
  background-color: #e6f7ff !important;
}

/* 新添加供应商的动画效果 */
@keyframes highlightPulse {
  0% { background-color: #f0f9ff; }
  50% { background-color: #e6f7ff; }
  100% { background-color: #f0f9ff; }
}

::v-deep .highlight-new-vendor {
  animation: highlightPulse 2s ease-in-out 3;
}

/* 选中行的样式 */
::v-deep .selected-row {
  background-color: #aaf3aa !important;
}

::v-deep .selected-row:hover {
  background-color: #ffcccc !important;
}

/* 确保选中行在hover状态下保持高亮 */
::v-deep .el-table__row.selected-row:hover > td {
  background-color: #ffcccc !important;
}
</style>
